package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.content.RoleRank;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIORunnable;
import com.vrv.app.cyberspace.common.ddio.TemplateMessage;
import com.vrv.app.cyberspace.config.WXBSystemConfig;
import com.vrv.app.cyberspace.modules.sys.entity.*;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.IDailyReportService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-15
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service("dailyReportServiceImpl")
@Transactional
public class DailyReportServiceImpl extends ServiceImpl<DailyReportMapper, DailyReport> implements IDailyReportService {
    Logger logger = LoggerFactory.getLogger(DailyReportServiceImpl.class);

    @Autowired
    private DailyReportMapper dailyReportMapper;
    @Autowired
    private FeedbackTableMapper feedbackTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private RoleTableMapper roleTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;
    @Autowired
    private WXBSystemConfig wxbSystemConfig;
    @Autowired
    private OrganizeTableMapper organizeTableMapper;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    @Transactional
    public Integer addupdateDailyReport(DailyReport dailyReport) {
        int result;
        try {
            dailyReport.setUnitIDsSet(dailyReport.getSelections());
            dailyReport.setCreateTime(new Date());
            //2. 新增每日零报告 插入DAILY_REPORT
            if (dailyReport.getId() == null)
                result = dailyReportMapper.insert(dailyReport);
            else
                result = dailyReportMapper.updateById(dailyReport);
        } catch (Exception e) {
            result = 0;
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void releaseDailyReport(DailyReport dailyReport) {
        try {
            //1.根据OrgID查询组织下的人员
            addOrUpdateDailyReport(dailyReport);
            //3.插入反馈表FEEDBACK_TABLE
            List<String> orgIDs = JSONArray.parseArray(dailyReport.getSelections(), String.class);
            insertFeedback(dailyReport, orgIDs);
            //4.推送模板消息
            pushMessageFromOrgID(dailyReport, orgIDs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addOrUpdateDailyReport(DailyReport dailyReport) {
        dailyReport.setUnitIDsSet(dailyReport.getSelections());
        dailyReport.setCreateTime(new Date());
        dailyReport.setIsRelease(1);//2.将指定每日零报告设置为发布状态
        //2.增加或更新DailyReport_table
        if (dailyReport.getId() == null) {
            dailyReportMapper.insert(dailyReport);
        } else {
            dailyReportMapper.updateById(dailyReport);
        }
    }

    private void pushMessageFromOrgID(DailyReport dailyReport, List<String> orgIDs) {
        List<UserTable> list = userTableMapper.selectList(new EntityWrapper<UserTable>().in("orgID", orgIDs));
        List<String> toUsers = new ArrayList<>();
        for (UserTable u : list) {
            toUsers.add(u.getLinkdoodID());
        }
        pushTemplateMessage(dailyReport, toUsers);
    }

    private void pushTemplateMessage(DailyReport dailyReport, List<String> toUsers) {
        String appid = apiV2Service.getAppID();
        String content = "标题: " + dailyReport.getTitle() + "\n发布人: " + dailyReport.getReleaseMan() + "\n发布单位: " + dailyReport.getReleaseUnit();
        TemplateMessage templateMessage = TemplateMessage.createOne(appid, "每日零报告", appid, content, wxbSystemConfig.getDailyReportDetailUrl() + "?id=" + dailyReport.getId(),
                StringUtils.join(toUsers.toArray(), ','));
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送每日零报告(ID" + dailyReport.getId() + ")消息失败! ");
            e.printStackTrace();
        }
    }

    @Override
    public void timedDailyReport() {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            DateFormat hm = new SimpleDateFormat("HH:mm");
            Date now = new Date();
            List<DailyReport> list = dailyReportMapper.selectList(new EntityWrapper<DailyReport>()
                    .ge("cycleEndTime", dateFormat.format(now))
                    .eq("dailyReleaseTime", hm.format(now)));
            for (DailyReport r : list) {
                List<String> orgIDs = JSONArray.parseArray(r.getUnitIDsSet(), String.class);
                insertFeedback(r, orgIDs);
                pushMessageFromOrgID(r, orgIDs);
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    private void insertFeedback(DailyReport dailyReport, List<String> list) throws CloneNotSupportedException {
        FeedbackTable feedbackTable = new FeedbackTable();
        feedbackTable.setReportID(dailyReport.getId());//关联每日零报告
        OrganizeTable organizeTable;
        for (String u : list) {
            feedbackTable.setFeedbackOrgID(u);
            organizeTable = organizeTableMapper.selectById(u);
            if (organizeTable != null)
                feedbackTable.setFeedbackUnit(organizeTable.getOrgName());
            List<UserTable> userTableList = userTableMapper.selectList(new EntityWrapper<UserTable>().eq("orgID", u));
            if (!CollectionUtils.isEmpty(userTableList)) {
                UserTable userTable = userTableList.get(0);
                feedbackTable.setWriterID(userTable.getLinkdoodID());
                feedbackTable.setWriterPhone(userTable.getCellphone());
                feedbackTable.setWriterName(userTable.getLinkdoodName());
            }
            feedbackTable.setCreateTime(new Date());
            feedbackTableMapper.insert(feedbackTable.clone());
        }
    }

    @Override
    public int deleteDailyReport(DailyReport dailyReport) {
        int result;
        //1.查询是否发布过,发布过就不让删除
        int count = feedbackTableMapper.selectCount(new EntityWrapper<FeedbackTable>().eq("reportID", dailyReport.getId()));
        if (count > 0) {//表示已经发布过,不容许删除
            result = -1;
        } else {
            result = dailyReportMapper.deleteById(dailyReport);
        }
        return result;
    }

    @Override
    public DailyReport detailDailyReport(Integer id) {
        DailyReport dailyReport = dailyReportMapper.selectById(id);
        if (dailyReport != null) {
            dailyReport.setHadFeedback(feedbackTableMapper.selectCount(new EntityWrapper<FeedbackTable>()
                    .eq("reportID", dailyReport.getId())
                    .in("feedbackOrgID", JSONArray.parseArray(dailyReport.getUnitIDsSet()))
                    .eq("isSubmit", 1)));
            List<String> orgs = JSON.parseArray(dailyReport.getUnitIDsSet(), String.class);
            if (!CollectionUtils.isEmpty(orgs))
                dailyReport.setOrgList(organizeTableMapper.selectBatchIds(orgs));
        }
        return dailyReport;
    }

    @Override
    public FeedbackTable detailSubDailyReport(Integer fId) {
        return feedbackTableMapper.selectByIdWithReport(fId);
    }

    /**
     * 0--在办；1--办结
     */
    @Override
    public Page<DailyReport> listDailyReport(Page<DailyReport> page, DailyReport dailyReport) {
        page.setAsc(false);
        page.setOrderByField("createTime");
        UserTable user = userTableMapper.selectById(dailyReport.getLinkdoodID());
        RoleTable roleTable = roleTableMapper.selectById(user.getRoleID());
        List<DailyReport> dailyReportList = new ArrayList<>();
        Integer flag = dailyReport.getFlag();
        Wrapper<DailyReport> ew = new EntityWrapper<DailyReport>();
        switch (RoleRank.create((roleTable != null ? roleTable.getRoleType() : ""))) {
            case LEADER://领导
                ew = ew.eq("isRelease", "1");
            case DUTY://值班员
                ewCreate(dailyReport, flag, ew);
                dailyReportList = dailyReportMapper.selectPage(page, ew);
                break;
            case LIAISONS:
            default://地方
                Wrapper<FeedbackTable> ewf = new EntityWrapper<FeedbackTable>().eq("feedbackOrgID", user.getOrgID()).eq("isSubmit", flag);
                if (StringUtils.isNoneEmpty(dailyReport.getStartTime()))
                    ewf.ge("createTime", dailyReport.getStartTime());
                if (StringUtils.isNoneEmpty(dailyReport.getEndTime()))
                    ewf.le("createTime", dailyReport.getEndTime());
                List<FeedbackTable> list = feedbackTableMapper.selectPage(page, ewf);
                DailyReport dr;
                for (FeedbackTable f : list) {
                    dr = dailyReportMapper.selectById(f.getReportID());
                    dr.setfId(f.getId());
                    dailyReportList.add(dr.clone());
                }
                break;
        }
        //获取每条每日零报告的已反馈数
        for (DailyReport d : dailyReportList) {
            d.setHadFeedback(feedbackTableMapper.selectCount(new EntityWrapper<FeedbackTable>()
                    .eq("reportID", d.getId())
                    .in("feedbackOrgID", JSONArray.parseArray(d.getUnitIDsSet()))
                    .eq("isSubmit", 1)));
        }
        page.setRecords(dailyReportList);
        return page;
    }

    private void ewCreate(DailyReport dailyReport, Integer flag, Wrapper<DailyReport> ew) {
        if (flag != null && flag == 0) {
            ew.ge("cycleEndTime", dateFormat.format(new Date()));
        } else {
            ew.lt("cycleEndTime", dateFormat.format(new Date()));
        }
        if (StringUtils.isNoneEmpty(dailyReport.getStartTime()))
            ew.ge("createTime", dailyReport.getStartTime());
        if (StringUtils.isNoneEmpty(dailyReport.getEndTime()))
            ew.le("createTime", dailyReport.getEndTime());
    }
}
